<template>
  <m-container class="password-set">
    <view class="password-set__title">
      {{ $t('设置密码') }}
    </view>
    <view class="password-set__subtitle">
      {{ $t('登录密码支持8-20个数字、字母、符号组合') }}
    </view>
    <m-form ref="loginForm" :model="loginForm" :rules="rules" :label-width="64" class="password-set__form">
      <m-form-item prop="firstPassword" border padding="35rpx 24rpx">
        <m-icon slot="label" name="lock" size="40" color="#999" />
        <input
          v-if="inputType === 'password'"
          :key="inputType"
          v-model="loginForm.oldPassword"
          type="password"
          maxlength="20"
          placeholder="请输入旧密码"
          :size="32"
        />
        <input
          v-if="inputType === 'text'"
          :key="inputType"
          v-model="loginForm.oldPassword"
          type="text"
          maxlength="20"
          placeholder="请输入旧密码"
          :size="32"
        />
        <m-icon slot="right" :name="showEye" size="40" color="#999" @click="handleToggle" />
      </m-form-item>
      <m-form-item prop="firstPassword" border padding="35rpx 24rpx">
        <m-icon slot="label" name="lock" size="40" color="#999" />
        <input
          v-if="inputType === 'password'"
          :key="inputType"
          v-model="loginForm.firstPassword"
          type="password"
          maxlength="20"
          placeholder="请输入新的登录密码"
          :size="32"
          @input="handleInput"
        />
        <input
          v-if="inputType === 'text'"
          :key="inputType"
          v-model="loginForm.firstPassword"
          type="text"
          maxlength="20"
          placeholder="请输入新的登录密码"
          :size="32"
          @input="handleInput"
        />
        <m-icon slot="right" :name="showEye" size="40" color="#999" @click="handleToggle" />
      </m-form-item>
      <m-form-item prop="secondPassword" border padding="35rpx 24rpx">
        <m-icon slot="label" name="lock" size="40" color="#999" />
        <input
          v-if="inputType === 'password'"
          :key="inputType"
          v-model="loginForm.secondPassword"
          type="password"
          maxlength="20"
          placeholder="确认新的登录密码"
          :size="32"
          @input="handleInput1"
        />
        <input
          v-if="inputType === 'text'"
          :key="inputType"
          v-model="loginForm.secondPassword"
          type="text"
          placeholder="确认新的登录密码"
          maxlength="20"
          :size="32"
          @input="handleInput1"
        />
        <m-icon slot="right" :name="showEye" size="40" color="#999" @click="handleToggle" />
      </m-form-item>
      <m-form-item label-width="0" padding="40rpx 0 32rpx 24rpx">
        <m-button size="xl" block :disabled="getDisabled" @click="submit('loginForm')">
          {{ $t('确认') }}
        </m-button>
      </m-form-item>
    </m-form>
  </m-container>
</template>

<script lang="ts">
import { defineComponent, computed, reactive, toRefs, nextTick } from '@vue/composition-api'
import getCurrentComponent from '@/utils/get-current-component'
import { useRouter } from '@/hooks'
import { minCache } from '@/utils/min-cache'
import store from '@/store/index'
import test from '@/utils/test'
import { updateUserPwd } from '@/api/modules/login'

export default defineComponent({
  setup() {
    const router = useRouter()
    const vm: any = getCurrentComponent()
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        const valid = test.password(value)

        if (valid) {
          callback()
        } else {
          callback(new Error('请将密码设置为8-20位，且由数字、字母、符号两种以上组合'))
        }
      }
    }

    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== loginForm.firstPassword) {
        callback(new Error('两次密码输入不一致，请重新输入!'))
      } else {
        callback()
      }
    }

    let loginForm = reactive({
      firstPassword: null,
      secondPassword: null,
      loginForm: null,
      oldPassword: null,
    })

    const state = reactive({
      inputType: 'password',
      inputTypeTwo: 'password',
      rules: {
        firstPassword: [
          {
            required: true,
            validator: validatePass,
          },
        ],
        secondPassword: [
          {
            required: true,
            validator: validatePass2,
          },
        ],
      },
    })
    const handleInput = (e) => {
      const str = e.detail.value || e.detail
      nextTick(() => {
        loginForm.firstPassword = str.replace(/[\s\u4e00-\u9fa5]/gi, '')
      })
    }
    const handleInput1 = (e) => {
      const str = e.detail.value || e.detail
      nextTick(() => {
        loginForm.secondPassword = str.replace(/[\s\u4e00-\u9fa5]/gi, '')
      })
    }
    // 登录按钮
    const submit = async (formName: any) => {
      const valid = await vm.$refs[formName].validate()
      if (!valid) {
        return
      }

      const { secondPassword, firstPassword, oldPassword }: any = loginForm
      if (secondPassword !== firstPassword) {
        uni.showToast({ title: '两次输入的密码不一样', icon: 'none' })
        return
      }

      try {
        await updateUserPwd({
          oldPassword,
          newPassword: secondPassword,
        })
        if (minCache.get('ut')) {
          store.dispatch('login/logout')
        }
        router.replaceAll({ name: 'UserLogin' })
      } catch (e: any) {
        uni.showToast({
          title: e.msg,
          icon: 'error',
        })
      }
    }

    const handleGoOneClickLogin = (params: any) => {
      router.push({ name: 'UserOneClickLogin' }, params)
    }

    const handleGoVcodeLogin = (params: any) => {
      router.push({ name: 'UserVcodeLogin' }, params)
    }

    const handleToggle = () => {
      state.inputType = state.inputType === 'password' ? 'text' : 'password'
    }

    const showEye = computed(() => (state.inputType === 'password' ? 'eye-hidden' : 'eye'))
    const getDisabled = computed(
      () =>
        !(
          loginForm.oldPassword &&
          loginForm.firstPassword &&
          (loginForm.firstPassword as any).trim() &&
          loginForm.secondPassword &&
          (loginForm.secondPassword as any).trim()
        )
    )

    return {
      ...toRefs(state),
      getDisabled,
      showEye,
      loginForm,
      submit,
      handleGoOneClickLogin,
      handleGoVcodeLogin,
      handleToggle,
      handleInput,
      handleInput1,
    }
  },
})
</script>

<style lang="scss">
.password-set {
  &__title {
    margin: 80rpx 72rpx 16rpx;
    font-size: 54rpx;
    font-weight: bold;;
  }
  &__subtitle {
    margin: 0 72rpx;
    color: $--font-secondary-c;
    font-size: 24rpx;
  }
  &__form {
    margin: 25rpx 24rpx 40rpx;
  }
  ::v-deep {
    .form-item {
      border-radius: 0;
    }
  }
}
</style>
